package com.fzu.normalservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fzu.commonutil.entity.Resource;
import com.fzu.commonutil.entity.RoleResource;
import com.fzu.commonutil.mapper.ResourceMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzu.commonutil.mapper.RoleResourceMapper;
import com.fzu.normalservice.param.ResourceParam;
import com.fzu.normalservice.result.ResourceTreeResult;
import com.fzu.normalservice.service.ResourceService;
import com.fzu.normalservice.service.RoleResourceService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyq
 * @since 2023-04-11
 */
@Service
@RequiredArgsConstructor
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {
    private final ResourceMapper resourceMapper;
    private final RoleResourceService roleResourceService;
    private final RoleResourceMapper roleResourceMapper;
    @Override
    public List<ResourceTreeResult> treeList() {
        LambdaQueryWrapper<Resource> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Resource::getParentId, 0);
        List<Resource> topList = super.list(wrapper);
        List<ResourceTreeResult> resultList = new ArrayList<>(topList.size());
        for (Resource resource : topList) {
            ResourceTreeResult result = new ResourceTreeResult();
            BeanUtils.copyProperties(resource, result);
            result.setChildren(resourceMapper.listByParentId(resource.getId()));
            resultList.add(result);
        }
        return resultList;
    }

    @Override
    public List<Resource> listByRoleId(Integer roleId) {
        LambdaQueryWrapper<RoleResource> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleResource::getRoleId, roleId);
        List<RoleResource> roleResourceList = roleResourceService.list(wrapper);
        List<Integer> resourceIds = roleResourceList.stream().map(RoleResource::getResourceId).collect(Collectors.toList());
        return resourceMapper.selectBatchIds(resourceIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ResourceParam param) {
        Integer roleId = param.getRoleId();
        roleResourceMapper.deleteOld(roleId);
        List<RoleResource> list = new ArrayList<>();
        for (Integer resourceId : param.getResourceIdList()) {
            list.add(new RoleResource().setResourceId(resourceId).setRoleId(roleId));
        }
        roleResourceService.saveBatch(list);
    }
}
